<?php

namespace App\Service\Coin;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\PayOrder;
use App\Model\Setting\TmpSetting;
use App\Model\UserPayBlacklist;
use App\Service\BaseService;

/**
 * 创建充值订单
 */
class CreateOrderService extends BaseService
{
    public function handle()
    {    
	$userId = $this->getUserId();
        $newPay = $this->curVersion >= env('NEW_PAYWAY_VERSION', '1.0.0');
        $clientIp = $this->request->server('remote_addr');
        $coin = $this->request->input('recharge_coin', 0);
	$version = $this->request->input('version', '1.0.0');
	$money = $this->request->input('pay_money', 0);
        $payChannel = $this->request->input('pay_channel', PayOrder::CHANNEL_WX);
        $subjectId = $this->request->input('subject_id', 1);

	//return $this->setError(ErrorCode::PARAMETER_ERROR, $newPay);
	//支付渠道：0-原生，1-杉德 3-新支付方式
	//$payFrom = PayOrder::getPayWay($payChannel, $newPay);
	$payFrom = $this->request->input('isWeb', 0);
        //斗拱支付
        //$payFrom = 4;	
	//return $this->setError(ErrorCode::PARAMETER_ERROR, [$payChannel,$payFrom]);

	//if ($userId == 61428) {
	//$payFrom = 0;
	//}

	//充值来源
        $from = $this->request->input('from', 0);

	 //屏蔽除新支付方式以外的其他支付方式
        //if ($payFrom !=3 || $payFrom !=4) {
//	if (!in_array($payFrom,array(3,4,5))) {    
//	    return $this->setError(ErrorCode::PARAMETER_ERROR, '该支付渠道已弃用～');
//        }

	 //微信先用老的支付方式
//      if (($payFrom == 4 || $payFrom == 5) && $payChannel == 'wechat') {
	if ($payChannel == 'wechat') {    
	    $payFrom = 3;
	}

	if ($payChannel == 'wechat' && $version != '1.3.39' ) {

		if( $version == '1.3.40' ){

		}else{
			$payFrom = 4;
		}
	    
	}



//	if ($payFrom == 5 && $payChannel == 'alipay') {
	if ($payChannel == 'alipay') {
	    if ($version == '1.3.39' || $version == '1.3.40') {
	    	$payFrom = 0;
	    } else {
	        $payFrom = 4;
	    }
	}
//return $this->setError(ErrorCode::PARAMETER_ERROR,[$payChannel,$payFrom]);
        if ($payFrom == 4) {
            if ($payChannel == 'wechat') {
                $payChannel = 'dg_wechat';
            } else if ($payChannel == 'alipay') {
                $payChannel = 'dg_alipay';
            }
	}
//return $this->setError(ErrorCode::PARAMETER_ERROR,[$payChannel,$payFrom]);
        if ( $payChannel == PayOrder::CHANNEL_APPLE
            || $payChannel == PayOrder::CHANNEL_SAND_WX || $payChannel == PayOrder::CHANNEL_SAND_ALI) {
            //return $this->setError(ErrorCode::PARAMETER_ERROR, '该充值方式已弃用～');
        }

	//支付宝支付暂时弃用
//        if ($payChannel == PayOrder::CHANNEL_ALI) {
//            return $this->setError(ErrorCode::PARAMETER_ERROR, '支付宝支付方式正在维护,请选择微信充值～');
//	}

        //支付宝暂时关闭
//        if (!$newPay && $payChannel == PayOrder::CHANNEL_ALI && $this->appId != 6) {
            //return $this->setError(ErrorCode::PARAMETER_ERROR, '支付宝暂未开通，请选择用微信充值～');
//        }
        //订单前检测
        if (PayOrder::FROM_ACT_DISCOUNT == $from) {
            $check = $this->checkActOrder($userId, $money, $coin, $payChannel);
            $subjectId = $check['subject_id'] ?? 0;
        } else {
            $check = $this->checkOrder($money, $subjectId, $payChannel, $userId);
        }
        //检测不通过    
        if ($check['errcode']) return $this->setError($check['errcode'], $check['errmsg']);
        //return $this->setError(ErrorCode::PARAMETER_ERROR, [$payFrom]);
//	 $userId = 26825;
	switch ($payFrom) {
            case PayOrder::PAY_FROM_NATIVE://支付渠道-原生
				$ret = PayOrder::createOrder($userId, $payChannel, $subjectId, $clientIp, $from);
                break;
            case PayOrder::PAY_FROM_SAND://支付渠道-杉德
                $payChannel =  $payChannel == PayOrder::CHANNEL_WX
                    ? PayOrder::CHANNEL_SAND_WX
                    : PayOrder::CHANNEL_SAND_ALI;
                $ret = PayOrder::createOrder($userId, $payChannel, $subjectId, $clientIp, $from);
		break;
	    case PayOrder::PAY_FROM_NEW://支付渠道-新支付
                $payChannel =  $payChannel == PayOrder::CHANNEL_WX
                    ? PayOrder::CHANNEL_NEW_WX
                    : PayOrder::CHANNEL_ALI;
                $ret = PayOrder::createOrderNew($userId, $payChannel, $subjectId, $clientIp, $from);
                break;
	
	    case PayOrder::PAY_FROM_DOUGONG://支付渠道-斗拱支付
                $payChannel =  $payChannel == PayOrder::CHANNEL_DOUGONG_WX
                    ? PayOrder::CHANNEL_DOUGONG_WX
                    : PayOrder::CHANNEL_DOUGONG_ALI;
                $ret_ori = PayOrder::createOrderDougong($userId, $payChannel, $subjectId, $clientIp, $from);
                break;
	}

//	if ($payFrom == PayOrder::PAY_FROM_NATIVE) {
//	return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$payFrom]);
//	}
	//    $ret = array();
        //    $ret['data']['pay_info'] =  $ret_ori['pay_info'];
        //    $ret['data']['order_id'] = $ret_ori['order_id'];
        //    $ret['payurl'] = $ret_ori['payurl'];
	    // return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$ret_ori]);
        //}
	//cs
	//return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$payFrom]);
	if ($payFrom == PayOrder::PAY_FROM_DOUGONG) {
	    $ret = array();
	    $ret['data']['pay_info']['code'] = 1;	
	    $ret['data']['pay_info']['payurl'] = $ret_ori['data']['qr_code']; 
	    $ret['order_id'] = $ret_ori['data']['req_seq_id'];
	    $ret['payurl'] = $ret_ori['data']['qr_code'];	    
	    if ($payChannel = 'dg_wechat') {
	     //   return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$ret_ori]);  	
	    }
	    //return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$ret_ori]);	
	}

        $ret['pay_from'] = $payFrom;
//	return $this->setError(ErrorCode::PARAMETER_ERROR, [$ret,$ret_ori]);
        //$ret['pay_from'] = $payFrom;
        log_user_result($userId, $ret);
        return $ret;
    }

    /**
     * 创建订单前检测
     */
    function checkOrder($money, $subjectId = 1, $payChannel = 'wechat', $userId)
    {
        if (!in_array($payChannel, PayOrder::CHANNEL_VALID)) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '支付方式有误~'];
        }
        $subject = ConfigUtil::getRecharge($subjectId, $payChannel);
        if (!$subject || $subject['rmb'] != $money) {
           return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '充值参数有误，请刷新页面重新提交订单~'];
	  // return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => [$subject,$money]];
	}

        //总充值限额
        // $allTotal = PayOrder::getSuccessTotal($userId);
        //当天充值限额
        // $todayTotal = PayOrder::getSuccessTotal($userId, date('Y-m-d'));
        //超过总限额
        // if (
        //     $allTotal >= TmpSetting::getPayTotal()
        //     && $todayTotal >= env('PAY_TOTAL_LMT_DAY', 50000)
        // ) {
        //     return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您在平台充值金额已达上限，请适度消费，理性交友！'];
        // }

        // 当天充值限额
        $todayTotal = PayOrder::getSuccessTotal($userId, date('Y-m-d'));

        $payLimitTaotal = config('busi.pay_limit_taotal');
        if(isset($payLimitTaotal[$userId])){
            #获取充值总金额
            $allTotal = PayOrder::getSuccessTotal($userId);
            #获取当日限制总额
            $payLimitTaotaLday = config('busi.pay_limit_taotal_day') ;
            $limitDay = isset($payLimitTaotaLday[$userId]) ? $payLimitTaotaLday[$userId] : 60000;#当日充值总额
            $togetherTotal = $todayTotal+$money*100;
            if($allTotal>=$payLimitTaotal[$userId] && $togetherTotal>=$limitDay){
                return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您当日充值已达上限，请适度消费，理性交友！'];
            }
        }

        // 限制用户ID
        $checkPayLimit = UserPayBlacklist::checkExclude($userId);

        $limitPay = config('busi.pay_limit');
        if ($checkPayLimit || (isset($limitPay[$userId]) && $todayTotal >= $limitPay[$userId])) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '您当日充值已达上限，请适度消费，理性交友！'];
        }
        return ['errcode' => 0];
    }

    /**
     * 创建订单前检测-活动充值
     */
    function checkActOrder($userId = 0, $money = 0, $coin = 0, $payChannel = 'wechat')
    {
        if (!in_array($payChannel, PayOrder::CHANNEL_VALID)) {
            return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '支付方式有误~'];
        }
        //是否首次充值
        if (!PayOrder::checkSuccessCount($userId)) $actConf = config('act.recharge.new');
        else {
            //是否今天有充值过
            if (PayOrder::checkSuccessCount($userId, date('Y-m-d'), true)) {
                return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '你今天已经充值过，无法参与优惠充值啦，请明天再来吧~'];
            }
            $actConf = config('act.recharge.old');
        }
        // if ($money != $actConf['new_price'] || $coin != $actConf['coin']) {
        //     return ['errcode' => ErrorCode::RECHARGE_PARAM_ERR, 'errmsg' => '充值参数有误，请刷新页面重新提交订单~'];
        // }
        return ['errcode' => 0, 'subject_id' => $actConf['subject_id']];
    }
}
